
import sys, os, struct, re

def convert_isim(base):
    fn0 = 'isim/%s_00.hex' % base
    fn1 = 'isim/%s_01.hex' % base

    f0 = open(fn0, 'w+')
    f1 = open(fn1, 'w+')

    lno = 0
    fb = open('inst/%s.inst' % base, 'rb')
    while True:
        d = fb.read(4)
        if len(d) != 4:
            break
        lno += 1
        d0, d1 = struct.unpack("HH", d)
        f0.write(f'{d0:04x}\n')
        f1.write(f'{d1:04x}\n')
    f0.close()
    f1.close()
    return lno

def convert_inst(base):
    fn0 = 'ihex/%s_00.dat' % base
    fn1 = 'ihex/%s_01.dat' % base

    f0 = open(fn0, 'w+')
    f1 = open(fn1, 'w+')

    f0.write("@0000\n")
    f1.write("@0000\n")

    lno = 0
    c = 0
    fb = open('inst/%s.inst' % base, 'rb')
    while True:
        d = fb.read(4)
        if len(d) == 0:
            break
        if len(d) != 4:
            print("error\n")
            break
        d0, d1 = struct.unpack("HH", d)
        f0.write(f'{d0:016b}\n')
        f1.write(f'{d1:016b}\n')
        c += 1
        lno += 1

    while c < 8192:
        d0, d1 = 0x0013, 0x0000
        f0.write(f'{d0:016b}\n')
        f1.write(f'{d1:016b}\n')
        c += 1

    f0.close()
    f1.close()
    return lno

def main():
    fn = sys.argv[1]
    base = fn[5:-5]
    convert_isim(base)
    n = convert_inst(base)
    f = open('cnt/%s.icnt' % base, 'w+')
    f.write("n = %d\n" % n)
    f.close()

if __name__=="__main__":
    main()

